04. Unidirectional Data Flow
Unidirectional Data Flow
Data-Binding In Other Frameworks
Front-end frameworks like Angular and Ember make use of two-way data bindings. In two-way data binding, the data is kept in sync throughout the app no matter where it is updated. If a model changes the data, then the data updates in the view. Alternatively, if the user changes the data in the view, then the data is updated in the model. Two-way data binding sounds really powerful, but it can make the application harder to reason about and know where the data is actually being updated.
Further Research
React's Data-flow
Data moves differently with React's unidirectional data flow. In React, the data flows from the parent component to a child component.
In the image above, we have two components:
- a parent component
- a child component
The data lives in the parent component and is passed down to the child component. Even though the data lives in the parent component, both the parent and the child components can use the data. However, if the data must be updated, then only the parent component should perform the update. If the child component needs to make a change to the data, then it would send the updated data to the parent component where the change will actually be made. Once the change is made in the parent component, the child component will be passed the data (that has just been updated!).
Now, this might seem like extra work, but having the data flow in one direction and having one place where the data is modified makes it much easier to understand how the application works.
Where to Change the Data?
SOLUTION:
- `FlightPlanner`
Now let's say that the FlightPlanner
component has two child components: LocationPicker
and DatePicker
. LocationPicker
itself is a parent component that has two child components: OriginPicker
and DestinationPicker
.
Where to Change the Data? 2
SOLUTION:
- `FlightPlanner`
- `LocationPicker`
Data Flow in React Recap
In React, data flows in only one direction, from parent to child. If data is shared between sibling child components, then the data should be stored in the parent component and passed to both of the child components that need it.